<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑零售出库' : '新增零售出库'"
    width="800px"
    :before-close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="100px"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="客户姓名" prop="customerName">
            <el-input v-model="formData.customerName" placeholder="请输入客户姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户电话" prop="customerPhone">
            <el-input v-model="formData.customerPhone" placeholder="请输入客户电话" />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-form-item label="商品信息" prop="products">
        <div class="product-table">
          <div class="table-header">
            <el-button type="primary" size="small" @click="addProduct">添加商品</el-button>
          </div>
          <el-table :data="formData.products" border style="width: 100%">
            <el-table-column prop="productName" label="商品名称" width="200">
              <template #default="scope">
                <el-input v-model="scope.row.productName" placeholder="请输入商品名称" />
              </template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量" width="100">
              <template #default="scope">
                <el-input-number 
                  v-model="scope.row.quantity" 
                  :min="1" 
                  :precision="0"
                  @change="calculateTotal"
                />
              </template>
            </el-table-column>
            <el-table-column prop="unitPrice" label="单价" width="120">
              <template #default="scope">
                <el-input-number 
                  v-model="scope.row.unitPrice" 
                  :min="0" 
                  :precision="2"
                  @change="calculateTotal"
                />
              </template>
            </el-table-column>
            <el-table-column prop="amount" label="金额" width="120">
              <template #default="scope">
                <span>{{ (scope.row.quantity * scope.row.unitPrice).toFixed(2) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80">
              <template #default="scope">
                <el-button 
                  type="danger" 
                  size="small" 
                  @click="removeProduct(scope.$index)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form-item>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="总金额" prop="totalAmount">
            <el-input-number 
              v-model="formData.totalAmount" 
              :min="0" 
              :precision="2"
              style="width: 100%"
              placeholder="请输入总金额"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="支付方式" prop="paymentMethod">
            <el-select v-model="formData.paymentMethod" placeholder="请选择支付方式" style="width: 100%">
              <el-option label="现金" value="cash" />
              <el-option label="微信" value="wechat" />
              <el-option label="支付宝" value="alipay" />
              <el-option label="银行卡" value="card" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-form-item label="备注" prop="remark">
        <el-input 
          v-model="formData.remark" 
          type="textarea" 
          :rows="3"
          placeholder="请输入备注信息"
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'

const dialogVisible = ref(false)
const isEdit = ref(false)
const submitLoading = ref(false)
const formRef = ref(null)

const formData = reactive({
  customerName: '',
  customerPhone: '',
  products: [],
  totalAmount: 0,
  paymentMethod: 'cash',
  remark: ''
})

const rules = {
  customerName: [
    { required: true, message: '请输入客户姓名', trigger: 'blur' }
  ],
  customerPhone: [
    { required: true, message: '请输入客户电话', trigger: 'blur' }
  ],
  products: [
    { 
      required: true, 
      validator: (rule, value, callback) => {
        if (!value || value.length === 0) {
          callback(new Error('请至少添加一个商品'))
        } else {
          callback()
        }
      }, 
      trigger: 'change' 
    }
  ],
  totalAmount: [
    { required: true, message: '请输入总金额', trigger: 'blur' }
  ],
  paymentMethod: [
    { required: true, message: '请选择支付方式', trigger: 'change' }
  ]
}

const open = (row = null) => {
  dialogVisible.value = true
  isEdit.value = !!row
  
  if (row) {
    // 编辑模式，填充数据
    Object.assign(formData, row)
  } else {
    // 新增模式，重置数据
    resetForm()
  }
}

const resetForm = () => {
  Object.assign(formData, {
    customerName: '',
    customerPhone: '',
    products: [],
    totalAmount: 0,
    paymentMethod: 'cash',
    remark: ''
  })
  formRef.value?.clearValidate()
}

const addProduct = () => {
  formData.products.push({
    productName: '',
    quantity: 1,
    unitPrice: 0,
    amount: 0
  })
}

const removeProduct = (index) => {
  formData.products.splice(index, 1)
  calculateTotal()
}

const calculateTotal = () => {
  const total = formData.products.reduce((sum, product) => {
    return sum + (product.quantity * product.unitPrice)
  }, 0)
  formData.totalAmount = total
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    // 模拟API调用
    setTimeout(() => {
      ElMessage.success(isEdit.value ? '编辑成功' : '新增成功')
      handleClose()
      submitLoading.value = false
    }, 1000)
  } catch (error) {
    console.log('表单验证失败', error)
  }
}

const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

// 暴露方法给父组件
defineExpose({
  open
})
</script>

<style scoped lang="less">
.product-table {
  .table-header {
    margin-bottom: 10px;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 